package com.zhuxulin.tab.bluetooth;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import com.zhuxulin.tab.utils.LogUtils;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.ParcelUuid;

public class Bluetooth {
	private static String TAG = Bluetooth.class.getSimpleName();
	private static Bluetooth BlueTooth = new Bluetooth();
	private InputStream inputStream = null;
	private OutputStream outputStream = null;
	private static UUID ID = UUID
			.fromString("00001101-0000-1000-8000-00805F9B34FB");
	protected BluetoothAdapter adapter = null;
	protected BluetoothDevice device = null;
	protected BluetoothSocket socket = null;

	private Bluetooth() {
		adapter = BluetoothAdapter.getDefaultAdapter();
		device = getBluetoothDevice();
		socket = createBluetoothSocket(device);
	}

	protected BluetoothDevice getBluetoothDevice() {
		BluetoothDevice device = null;
		if (adapter == null) {
			LogUtils.i(TAG, "adapter is null can not get blue tooth device!");
			return null;
		}
		LogUtils.i(TAG, "Begin getBluetoothDevice!");
		device = adapter.getBondedDevices().iterator().next();
		LogUtils.i(TAG, "End getBluetoothDevice!Add:" + device.getAddress()
				+ "Name:" + device.getName() + "UUIDs:" + device.getUuids());
		for (ParcelUuid p : device.getUuids()) {
			LogUtils.i(TAG, "P:" + p.toString());
			LogUtils.i(TAG, "UUID:" + p.getUuid().toString());
		}
		return device;
	}

	protected BluetoothSocket createBluetoothSocket(BluetoothDevice device) {
		if (device == null) {
			LogUtils.i(TAG, "Device is null can not create socket!");
			return null;
		}
		BluetoothSocket socket = null;
		try {
			LogUtils.i(TAG,
					"Use UUID to create socket at createBluetoothSocket(BluetoothDevice device)");
			// adapter.listenUsingInsecureRfcommWithServiceRecord(name, id);
			// return device.createRfcommSocketToServiceRecord(id);
			socket = device.createInsecureRfcommSocketToServiceRecord(ID);
			LogUtils.i(TAG, "Use UUID to create socket successful!");
			LogUtils.i(TAG, "Socket:" + socket.toString());
			return socket;
		} catch (IOException e) {
			LogUtils.e(TAG,
					"Throws exception at createBluetoothSocket(BluetoothDevice device)");
			e.printStackTrace();
			return null;
		}
	}

	public static Bluetooth getBluetooth() {
		return BlueTooth;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public OutputStream getOutputStream() {
		return outputStream;
	}

	public void setOutputStream(OutputStream outputStream) {
		this.outputStream = outputStream;
	}
}
